#!/usr/bin/python
#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.

import matplotlib
matplotlib.use('AGG')
from matplotlib import pyplot

import collections
import numpy
import os
import struct
import sys
import time
import vuze_util

import log_parser

def plot_arrival_times(arrival_times, name, hop_start_time):
  total_arrivals = float(sum(arrival_times.itervalues()))
  t0 = hop_start_time
  tmax = max(arrival_times.iterkeys())
  arrivals = [(x-t0, arrival_times[x]) for x in sorted(arrival_times.iterkeys())]

  total_arrival_times = sum(time * count for (time, count) in arrivals)
  total_counts = sum(count for (time, count) in arrivals)
  print 'Average arrival time: %f' % (float(total_arrival_times) / total_counts)

  fig = pyplot.figure()
  ax = fig.add_subplot(111)

  ax.bar([x[0] for x in arrivals], [x[1] for x in arrivals], width=1)
  ax.set_title('PDF of packet arrivals')
  ax.set_xlabel('Time since hop start (s)')
  ax.set_ylabel('Count of packets arrived in interval')
  pyplot.savefig('arrivals%s.png' % name, format='png')


# Now plot CDF
  pyplot.close()
  pyplot.cla()
  fig.clear()
  fig = pyplot.figure()
  ax = fig.add_subplot(111)

  cdf = [(k, sum(y for (x,y) in arrivals[0:idx+1]) / total_arrivals) for (idx, (k, v)) in enumerate(arrivals)]

  ax.plot([x[0] for x in cdf], [x[1] for x in cdf])
  ax.set_title('CDF of packet arrivals')
  ax.set_xlabel('Time since hop start (s)')
  ax.set_ylabel('Total packets arrived by time')
  pyplot.savefig('arrivalcdf%s.png' % name, format='png')
#   g.title('PDF of packet arrivals for %s' % name)
# #  g('set xrange [0:]')
# #  g('set yrange [0:1]')
#   g('set xlabel "Time since first arrival[s]"')
#   g('set ylabel "Count of packets arrived at time"')
#   d = Gnuplot.Data(arrivals, with_='linespoints')
#   g('set output "arrivals%s.png"' % name)
#   g('set terminal png')
#   g.plot(d)
#   g('set terminal pop')
  

def main():
  hop_start_timestamp = time.mktime(time.strptime(sys.argv[1]))

  has_originator = int(sys.argv[2])

  arrival_times = collections.defaultdict(int)
  for log in sys.argv[3:]:
    arrival_times = collections.defaultdict(int) # default zero
    
    log_list = log_parser.get_stores(log, has_originator)
    if not log_list:
      continue

    for log_record in log_list:
      arrival_times[log_record[1]] += 1


  plot_arrival_times(arrival_times, 'all', hop_start_timestamp)

if __name__ == '__main__':
  main()
